package com.payment.ktb.activity.main4;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideTopExit;
import com.flyco.dialog.widget.popup.base.BasePopup;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.adapter.OrderCenterAdapter;
import com.payment.ktb.constants.ConstantsPay;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.model.OrderCenterEntity;
import com.payment.ktb.model.OrderCenterFullEntity;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.LogUtil;
import com.payment.ktb.utils.ToastUtils;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/9/2.
 */

public class OrderCenterActivity extends BaseActivity implements AdapterView.OnItemClickListener {



    @BindView(R.id.iv_ordercenter_date_arror)
    ImageView iv_ordercenter_date_arror;
    @BindView(R.id.iv_ordercenter_type_arror)
    ImageView iv_ordercenter_type_arror;
    @BindView(R.id.rl_ordercenter_type)
    RelativeLayout rl_ordercenter_type;
    @BindView(R.id.rl_ordercenter_date)
    RelativeLayout rl_ordercenter_date;
    @BindView(R.id.tv_ordercenter_type)
    TextView tv_ordercenter_type;
    @BindView(R.id.prlv_ordercenter)
    PullToRefreshListView prlv_ordercenter;
    TextView tv_ordercenter_date_starttime;
    TextView tv_ordercenter_date_endtime;
    private SimpleCustomPopOrderType mQuickCustomPopupOrderType;
    private SimpleCustomPopOrderDate mQuickCustomPopupOrderDate;
    private List<OrderCenterEntity> listDatas = new ArrayList<>();
    private OrderCenterAdapter orderCenterAdapter;
    private String product = "";
    String ts = null;
    String te = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 23:59:59";
    int page = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ordercenter);
        initTitle("订单中心");
        ButterKnife.bind(this);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE,-7);
        ts = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " 00:00:00";
        mQuickCustomPopupOrderType = new SimpleCustomPopOrderType(mContext);
        mQuickCustomPopupOrderDate = new SimpleCustomPopOrderDate(mContext);

        prlv_ordercenter.setMode(PullToRefreshBase.Mode.BOTH);
        prlv_ordercenter.setOnItemClickListener(this);
        prlv_ordercenter.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                // 设置下拉刷新加载文本
                prlv_ordercenter.getLoadingLayoutProxy(true, false).setPullLabel("下拉刷新...");
                prlv_ordercenter.getLoadingLayoutProxy(true, false).setReleaseLabel("放开刷新...");
                prlv_ordercenter.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在加载...");
                //下拉刷新
                pullDownToRefresh();
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 设置上拉加载文本
                prlv_ordercenter.getLoadingLayoutProxy(false, true).setPullLabel("上拉刷新...");
                prlv_ordercenter.getLoadingLayoutProxy(false, true).setReleaseLabel("放开刷新...");
                prlv_ordercenter.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载...");
                pullUptoLoad();


            }
        });
        pullDownToRefresh();


    }

    private void pullUptoLoad() {



        progressDialogUtils.showProgress();
        //构造传输参数
        page = page + 1;
        Map<String, String> map = new HashMap<String,String>();
        map.put("ts",ts);
        map.put("te",te);
        map.put("product",product);
        map.put("page", String.valueOf(page));
        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.PayOrderList, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();
                prlv_ordercenter.onRefreshComplete();
                //data
                JSONObject responseJson = JSON.parseObject(response);
                JSONObject recordsJson = responseJson.getJSONObject("records");
                for (String key:recordsJson.keySet()) {
                    OrderCenterEntity orderCenterDateEntity = new OrderCenterEntity();
                    orderCenterDateEntity.setDate(key);
                    listDatas.add(orderCenterDateEntity);
                    List<OrderCenterFullEntity> ordercenterfullentities= new Gson().fromJson(recordsJson.getString(key), new TypeToken<List<OrderCenterFullEntity>>() {
                    }.getType());
                    for (OrderCenterFullEntity orderCenterFullEntity:ordercenterfullentities) {
                        OrderCenterEntity orderCenterContentEntity = new OrderCenterEntity();
                        orderCenterContentEntity.setPrice(orderCenterFullEntity.getOrderPrice());
                        orderCenterContentEntity.setType(orderCenterFullEntity.getGoodsName());
                        orderCenterContentEntity.setTime(orderCenterFullEntity.getOrderReqTime());
                        orderCenterContentEntity.setStatus(orderCenterFullEntity.getOrderStatusName());
                        orderCenterContentEntity.setCardBank(orderCenterFullEntity.getCardBank());
                        orderCenterContentEntity.setCardNo(orderCenterFullEntity.getCardNo());
                        orderCenterContentEntity.setOrderNo(orderCenterFullEntity.getOrderNo());
                        orderCenterContentEntity.setProduct(orderCenterFullEntity.getProduct());
                        listDatas.add(orderCenterContentEntity);
                    }
                }

                //adapter
                orderCenterAdapter.notifyDataSetChanged();


            }
            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                prlv_ordercenter.onRefreshComplete();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });







    }

    private void pullDownToRefresh() {

        progressDialogUtils.showProgress();
        //构造传输参数
        page = 0;
        Map<String, String> map = new HashMap<String,String>();
        map.put("ts",ts);
        map.put("te",te);
        map.put("product",product);
        map.put("page", String.valueOf(page));
        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.PayOrderList, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();
                prlv_ordercenter.onRefreshComplete();
                listDatas.clear();
                //data
                JSONObject responseJson = JSON.parseObject(response);
                JSONObject recordsJson = responseJson.getJSONObject("records");
                for (String key:recordsJson.keySet()) {
                    OrderCenterEntity orderCenterDateEntity = new OrderCenterEntity();
                    orderCenterDateEntity.setDate(key);
                    listDatas.add(orderCenterDateEntity);
                    List<OrderCenterFullEntity> ordercenterfullentities= new Gson().fromJson(recordsJson.getString(key), new TypeToken<List<OrderCenterFullEntity>>() {
                    }.getType());
                    for (OrderCenterFullEntity orderCenterFullEntity:ordercenterfullentities) {
                        OrderCenterEntity orderCenterContentEntity = new OrderCenterEntity();
                        orderCenterContentEntity.setPrice(orderCenterFullEntity.getOrderPrice());
                        orderCenterContentEntity.setType(orderCenterFullEntity.getGoodsName());
                        orderCenterContentEntity.setTime(orderCenterFullEntity.getOrderReqTime());
                        orderCenterContentEntity.setStatus(orderCenterFullEntity.getOrderStatusName());
                        orderCenterContentEntity.setCardBank(orderCenterFullEntity.getCardBank());
                        orderCenterContentEntity.setCardNo(orderCenterFullEntity.getCardNo());
                        orderCenterContentEntity.setOrderNo(orderCenterFullEntity.getOrderNo());
                        orderCenterContentEntity.setProduct(orderCenterFullEntity.getProduct());
                        listDatas.add(orderCenterContentEntity);
                    }
                }

                //adapter
                orderCenterAdapter = new OrderCenterAdapter(mContext, listDatas);
                //bind
                prlv_ordercenter.setAdapter(orderCenterAdapter);

            }
            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                prlv_ordercenter.onRefreshComplete();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });







    }


    @OnClick({R.id.rl_ordercenter_date,R.id.rl_ordercenter_type})
    public void clickEvent(View view){

        switch (view.getId()){

            case R.id.rl_ordercenter_date:


                if (mQuickCustomPopupOrderDate.isShowing()){
                    mQuickCustomPopupOrderDate.dismiss();
                    iv_ordercenter_date_arror.setImageResource(R.mipmap.order_arror_down);
                }else {
                    mQuickCustomPopupOrderDate
                            .offset(0, 5)
                            .anchorView(rl_ordercenter_date)
                            .gravity(Gravity.BOTTOM)
                            .showAnim(new BounceTopEnter())
                            .dismissAnim(new SlideTopExit())
                            .dimEnabled(false)
                            .show();
                    iv_ordercenter_date_arror.setImageResource(R.mipmap.order_arror_up);
                }


                break;

            case R.id.rl_ordercenter_type:

                if (mQuickCustomPopupOrderType.isShowing()){
                    mQuickCustomPopupOrderType.dismiss();
                    iv_ordercenter_type_arror.setImageResource(R.mipmap.order_arror_down);
                }else {
                    mQuickCustomPopupOrderType
                            .offset(0, 5)
                            .anchorView(rl_ordercenter_type)
                            .gravity(Gravity.BOTTOM)
                            .showAnim(new BounceTopEnter())
                            .dismissAnim(new SlideTopExit())
                            .dimEnabled(false)
                            .show();
                    iv_ordercenter_type_arror.setImageResource(R.mipmap.order_arror_up);
                }
                break;
        }
    }




    /**
     *
     */
    private void showStartDateDialog() {

        ToastUtils.showToast("请选择开始时间！");
        new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String time = String.format("%d-%d-%d",year,monthOfYear + 1,dayOfMonth);
                ts = time + " 00:00:00";
                tv_ordercenter_date_starttime.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, Calendar.getInstance().get(Calendar.YEAR),Calendar.getInstance().get(Calendar.MONTH),Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).show();
    }



    /**
     *
     */
    private void showEndDateDialog() {

        ToastUtils.showToast("请选择结束时间！");
        new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String time = String.format("%d-%d-%d",year,monthOfYear + 1,dayOfMonth);
                te = time + " 23:59:59";
                tv_ordercenter_date_endtime.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, Calendar.getInstance().get(Calendar.YEAR),Calendar.getInstance().get(Calendar.MONTH),Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).show();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        i = i - 1;

        if (TextUtils.isEmpty(listDatas.get(i).getDate())) {
            Intent intent = new Intent(mContext,OrderCenterResultActivity.class);
            intent.putExtra("orderPrice",listDatas.get(i).getPrice());
            intent.putExtra("orderStatusName",listDatas.get(i).getStatus());
            if (listDatas.get(i).getProduct().equals("1000")){
                intent.putExtra("goodsName","商户收款");
            }else if (listDatas.get(i).getProduct().equals("1001")) {
                intent.putExtra("goodsName","会员购买");
            }else if (listDatas.get(i).getProduct().equals("1002")) {
                intent.putExtra("goodsName","后台管理费");
            }else {
                intent.putExtra("goodsName","商户收款");
            }

            intent.putExtra("cardBank",listDatas.get(i).getCardBank());
            intent.putExtra("cardNo",listDatas.get(i).getCardNo());
            intent.putExtra("orderNo",listDatas.get(i).getOrderNo());
            intent.putExtra("orderReqTime",listDatas.get(i).getTime());
            startActivity(intent);
        }
    }


    class SimpleCustomPopOrderType extends BasePopup<SimpleCustomPopOrderType> {

       @BindView(R.id.rl_ordercenter_type_item1)
       RelativeLayout rl_ordercenter_type_item1;
       @BindView(R.id.rl_ordercenter_type_item2)
       RelativeLayout rl_ordercenter_type_item2;
       @BindView(R.id.rl_ordercenter_type_item3)
       RelativeLayout rl_ordercenter_type_item3;
       @BindView(R.id.rl_ordercenter_type_item4)
       RelativeLayout rl_ordercenter_type_item4;
       @BindView(R.id.iv_ordercenter_type_item1)
       ImageView iv_ordercenter_type_item1;
       @BindView(R.id.iv_ordercenter_type_item2)
       ImageView iv_ordercenter_type_item2;
       @BindView(R.id.iv_ordercenter_type_item3)
       ImageView iv_ordercenter_type_item3;
       @BindView(R.id.iv_ordercenter_type_item4)
       ImageView iv_ordercenter_type_item4;
       @BindView(R.id.tv_ordercenter_type_item1)
       TextView tv_ordercenter_type_item1;
       @BindView(R.id.tv_ordercenter_type_item2)
       TextView tv_ordercenter_type_item2;
       @BindView(R.id.tv_ordercenter_type_item3)
       TextView tv_ordercenter_type_item3;
       @BindView(R.id.tv_ordercenter_type_item4)
       TextView tv_ordercenter_type_item4;






        public SimpleCustomPopOrderType(Context context) {
            super(context);
          //setCanceledOnTouchOutside(false);
        }

        @Override
        public View onCreatePopupView() {
            View inflate = View.inflate(mContext, R.layout.dialog_ordercenter_ordertype, null);
            ButterKnife.bind(this, inflate);
            return inflate;
        }

        @Override
        public void setUiBeforShow() {
            rl_ordercenter_type_item1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    iv_ordercenter_type_item1.setVisibility(View.VISIBLE);
                    iv_ordercenter_type_item2.setVisibility(View.GONE);
                    iv_ordercenter_type_item3.setVisibility(View.GONE);
                    iv_ordercenter_type_item4.setVisibility(View.GONE);
                    mQuickCustomPopupOrderType.dismiss();
                    iv_ordercenter_type_arror.setImageResource(R.mipmap.order_arror_down);
                    tv_ordercenter_type.setText(tv_ordercenter_type_item1.getText());
                    product = "";
                    pullDownToRefresh();

                }
            });
            rl_ordercenter_type_item2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    iv_ordercenter_type_item2.setVisibility(View.VISIBLE);
                    iv_ordercenter_type_item1.setVisibility(View.GONE);
                    iv_ordercenter_type_item3.setVisibility(View.GONE);
                    iv_ordercenter_type_item4.setVisibility(View.GONE);
                    mQuickCustomPopupOrderType.dismiss();
                    iv_ordercenter_type_arror.setImageResource(R.mipmap.order_arror_down);
                    tv_ordercenter_type.setText(tv_ordercenter_type_item2.getText());
                    product = ConstantsPay.product1000;
                    pullDownToRefresh();
                }
            });
            rl_ordercenter_type_item3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    iv_ordercenter_type_item3.setVisibility(View.VISIBLE);
                    iv_ordercenter_type_item1.setVisibility(View.GONE);
                    iv_ordercenter_type_item2.setVisibility(View.GONE);
                    iv_ordercenter_type_item4.setVisibility(View.GONE);
                    mQuickCustomPopupOrderType.dismiss();
                    iv_ordercenter_type_arror.setImageResource(R.mipmap.order_arror_down);
                    tv_ordercenter_type.setText(tv_ordercenter_type_item3.getText());
                    product = ConstantsPay.product1001;
                    pullDownToRefresh();

                }
            });
            rl_ordercenter_type_item4.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    iv_ordercenter_type_item4.setVisibility(View.VISIBLE);
                    iv_ordercenter_type_item1.setVisibility(View.GONE);
                    iv_ordercenter_type_item2.setVisibility(View.GONE);
                    iv_ordercenter_type_item3.setVisibility(View.GONE);
                    mQuickCustomPopupOrderType.dismiss();
                    iv_ordercenter_type_arror.setImageResource(R.mipmap.order_arror_down);
                    tv_ordercenter_type.setText(tv_ordercenter_type_item4.getText());
                    product = ConstantsPay.product1002;
                    pullDownToRefresh();
                }
            });
        }
    }











    class SimpleCustomPopOrderDate extends BasePopup<SimpleCustomPopOrderDate> {

       @BindView(R.id.rl_ordercenter_date_delete)
       RelativeLayout rl_ordercenter_date_delete;
       @BindView(R.id.btn_ordercenter_date_confirm)
       Button btn_ordercenter_date_confirm;




        public SimpleCustomPopOrderDate(Context context) {
            super(context);
          //setCanceledOnTouchOutside(false);
        }

        @Override
        public View onCreatePopupView() {
            View inflate = View.inflate(mContext, R.layout.dialog_ordercenter_orderdate, null);
            tv_ordercenter_date_starttime = (TextView) inflate.findViewById(R.id.tv_ordercenter_date_starttime);
            tv_ordercenter_date_endtime = (TextView) inflate.findViewById(R.id.tv_ordercenter_date_endtime);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DATE,-7);
            tv_ordercenter_date_starttime.setText(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
            tv_ordercenter_date_endtime.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

            ButterKnife.bind(this, inflate);
            return inflate;
        }

        @Override
        public void setUiBeforShow() {
            rl_ordercenter_date_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mQuickCustomPopupOrderDate.dismiss();
                    iv_ordercenter_date_arror.setImageResource(R.mipmap.order_arror_down);
                }
            });
            btn_ordercenter_date_confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mQuickCustomPopupOrderDate.dismiss();
                    iv_ordercenter_date_arror.setImageResource(R.mipmap.order_arror_down);
                    pullDownToRefresh();
                }
            });
            tv_ordercenter_date_starttime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showStartDateDialog();
                }
            });
            tv_ordercenter_date_endtime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEndDateDialog();
                }
            });
        }
    }





}
